'''
1.time.sleep() 强制等待

2.driver.implicitly_wait() 隐式等待 就是我最多同意加载1分钟,一分钟内完成就加载，一分钟之后就不等待了

3.显式等待 我以某个参照物 确认是否还继续等待
'''


import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 强制等待
def wait1(d, **key):
    '''强制等待'''
    try:
        sec = key.get('sec')
        sec = int(sec)
    except:
        print('sec转类型异常,进入默认模式')
        sec = 10
    time.sleep(sec)


# 隐式等待
def wait2(d, **key):
    '''隐式等待'''
    try:
        sec = key.get('sec')
        sec = int(sec)
    except:
        print('sec转类型异常,进入默认模式')
        sec = 10
    d.implicitly_wait(sec)

# 显式等待
# 其实不适合扒数据，反而适合莫某些按键精灵
def wait3(d, **key):
    '''
        显式等待
        1.presence_of_element_located()      元素存在
        2.visibility_of_element_located()    元素可见
        3.element_to_be_clickable()          元素可点击
        4.title_contains()                   标题包括的类容【这应该是窗口标题】
        5.new_window_is_opened()             新窗口打开
        6.frame_to_be_available_and_switch_to_it()   加载切换到iframe
        7.alert_is_present()                 弹框出现
    '''
    try:
        sec = key.get('sec')
        sec = int(sec)
    except:
        print('sec转类型异常,进入默认模式')
        sec = 10

    try:
        frequency = key.get('frequency')
        frequency = float(frequency)
    except:
        print('frequency转类型异常,进入默认模式')
        frequency = 0.2

    WebDriverWait(d, sec, frequency).until(
        EC.element_to_be_clickable((By.XPATH, '//button[@class="el-button el-button--danger el-button--default"]'))
    )


#
def liuyan(wait, err=0, max_err=10, **key):
    print(f'err:{err}, max_err:{max_err},key:{key}')
    driver = webdriver.Chrome()
    try:
        driver.get('http://liuyan.people.com.cn/threads/list?fid=5210&formName=%E4%B8%AD%E5%8D%8E%E5%85%A8%E5%9B%BD%E6%80%BB%E5%B7%A5%E4%BC%9A%E5%85%9A%E7%BB%84%E4%B9%A6%E8%AE%B0%E3%80%81%E5%89%AF%E4%B8%BB%E5%B8%AD%E3%80%81%E4%B9%A6%E8%AE%B0%E5%A4%84%E7%AC%AC%E4%B8%80%E4%B9%A6%E8%AE%B0%E5%BE%90%E7%95%99%E5%B9%B3&position=1')
        wait(driver, **key)
        data_lis = driver.find_elements(By.XPATH, '//ul[@class="replyList"]/li')
        for li in data_lis:
            t2 = li.find_element(By.XPATH, './p[@class="replyContent"]/span[1]').text
            print(t2)
    except:
        print('报错了')
        err = err+1
        if err < max_err:
            liuyan(wait, err=err + 1,max_err=max_err, **key)
    finally:
        print('关闭driver')
        driver.quit()


if __name__ == '__main__':
    # liuyan(wait1, sec='lala')
    # liuyan(wait2)
    liuyan(wait3, sec=30, frequency=3)







